package net.sipvip.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class GeneralInfoServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(GeneralInfoServlet.class
			.getName());

	// List<Users> userList = new ArrayList<Users>();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.info("Start GeneralInfoServlet");
		JSONArray videojarray = new JSONArray();
		req.getRemoteHost();
		String city = req.getParameter("city");
		String cookies = req.getParameter("cookies");
		String ip = req.getRemoteHost();
		String country = req.getParameter("country");

		Date dateNow = new Date();
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		StringBuilder now = new StringBuilder(df.format(dateNow));
		String nowstr = now.toString();

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query q = pm.newQuery(Users.class, "cookies == '" + cookies + "'");
		// Query q = pm.newQuery(Users.class);

		List<Users> results = (List<Users>) q.execute();

		int k = results.size();

		if (k == 0) {

			try {
				pm.makePersistent(new Users(cookies, ip, nowstr, nowstr, city,
						country, 1));

			} finally {
				pm.close();

			}
		} else {

			if (results.iterator().hasNext()) {
				for (Users e : results) {

					int count_visit = e.getVisit_counter();
					e.setVisit_counter(count_visit + 1);
					e.setUpdae_date(dateNow);

				}
			}

			// results.clear();
			k = 0;
			Query qv = pm
					.newQuery(Videos.class, "cookies == '" + cookies + "'");
			qv.setOrdering("create_date descending");
			qv.setRange(0, 25);
//			qv.setUnique(true);

			List<Videos> vresults = (List<Videos>) qv.execute();
			
			k = results.size();

			if (k > 0) {

				if (vresults.iterator().hasNext()) {
					for (Videos e : vresults) {

						log.info(e.getImage());
						// int count_visit = e.getVisit_counter();
						// e.setVisit_counter(count_visit + 1);
						// e.setUpdae_date(dateNow);
						JSONObject obj = new JSONObject();
						obj.put("video",e.getVideo());
						obj.put("image",e.getImage());
						obj.put("description",e.getDescription());
						videojarray.add(obj);
												
					}
				}

			}
			
			pm.close();
		}

		String output = req.getParameter("callback") + "(" + videojarray + ");";
		resp.setContentType("text/javascript");

		PrintWriter out = resp.getWriter();
		out.println(output);

	}

}
